package Twitim::Twitim;

use strict;
use warnings;
use Glib qw(TRUE FALSE);
use Gtk2;
use Twitim::L10N;
use Exporter;

our @ISA = qw(Exporter);
our @EXPORT
    = qw(get_tagged_text open_url text_entry set_label make_dialog);

our $www_browser = "xdg-open";

# Open URL with browser

sub open_url {
    my $url = shift;
    system("$www_browser $url 2> /dev/null &");
}

# Get Tagged Text

sub get_tagged_text {
    my ( $text_view, $iter, $tag ) = @_;
    my $buffer = $text_view->get_buffer;

    $iter->forward_char if $iter->begins_tag($tag);

    $iter->backward_to_tag_toggle($tag);
    my $start = $buffer->create_mark( 'tagstart', $iter, 0 );
    $iter->forward_to_tag_toggle($tag);
    my $end = $buffer->create_mark( 'tagend', $iter, 0 );

    my $string = $buffer->get_text( $buffer->get_iter_at_mark($start),
        $buffer->get_iter_at_mark($end), 1 );

    return $string;
}

#######################
# GUI parts

sub text_entry {
    my ( $parent, $name, $text, $n, $secret, $return_label, $widget ) = @_;
    $n ||= 0;

    $widget->set_alignment( 0.0, 0.5 ) if $widget;
    $widget ||= Gtk2::Entry->new();

    $widget->set_text($text) if $text;
    my $label = set_label( $parent, $name, $n, undef, $widget );

    # $widget->set_padding(10, 10);
    $widget->set_visibility(FALSE) if ( $n && !defined $secret );
    $parent->attach_defaults( $widget, 1, 2, 0 + $n, 1 + $n );

    return ( $widget, $label ) if $return_label;
    return $widget;
}

sub set_label {
    my ( $parent, $name, $row, $col, $relate, $bold, $padding ) = @_;

    $row ||= 0;
    $col ||= 0;
    $padding ||= 0;

    my $text = l10n($name) . ":";
    $text = "<b>$text</b>" if $bold;
    my $widget = Gtk2::Label->new;
    $widget->set_markup_with_mnemonic($text);
    $widget->set_mnemonic_widget($relate) if $relate;

    # $widget->set_width_chars (10);
    # $widget->set_padding(0, 10);
    $widget->set_alignment( 0.0, 0.5 );

    my $alignment = Gtk2::Alignment->new( 0.5, 0.5, 1.0, 1.0 );
    $alignment->set_padding( 0, 0, $padding, 0 );
    $alignment->add($widget);

    $parent->attach(
        $alignment, 0 + $col, 1 + $col, 0 + $row, 1 + $row, ['fill'],
        'shrink', 0, 0
    );

    return $widget;
}

sub make_dialog {
    my ( $text1, $text2, $parent, $type, $button ) = @_;

    my $dialog
        = Gtk2::MessageDialog->new_with_markup( $parent,
        [qw/modal destroy-with-parent/],
        $type, $button, "<big><b>" . l10n($text1) . "</b></big>" );
    $dialog->format_secondary_markup( l10n($text2) );
    $dialog->set_title($main::APP_NAME) unless ( defined $parent );
    $dialog->set_icon_from_file('/etc/twitim/twitim.png')
        if ( -e '/etc/twitim/twitim.png' );

    my $response = $dialog->run;
    $dialog->destroy;

    return $response;
}

1;
